package util

import (
	"time"
	"toy-car/pkg/setting"

	jwt "github.com/dgrijalva/jwt-go"
)

var jwtSecret = []byte(setting.JwtSecret)

type Claims struct {
	Username   string `json:"username"`
	NickName   string `json:"nickname"`
	UserID     int64  `json:"user_id"`
	UserType   int    `json:"user_type"`
	BufferTime int64
	jwt.StandardClaims
}

func GenerateToken(loginName, showName string, userID int64, UserType int) (string, error) {
	nowTime := time.Now()
	expireTime := nowTime.Add(3 * time.Hour)

	claims := Claims{
		loginName,
		showName,
		userID,
		UserType,
		setting.JwtBufferTime,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "toy-car",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(jwtSecret)

	return token, err
}

func ReGenerateToken(c *Claims) (string, error) {
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	return tokenClaims.SignedString(jwtSecret)
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}
	return nil, err
}
